<template>
  <el-card class="preference-panel" shadow="hover" v-loading="loading">
    <!-- <template #header>
      <div class="card-header">
        <div class="card-header-text">账号偏好设置</div>
      </div>
    </template> -->

    <el-form :model="preference" label-width="auto" v-if="preference">
      <el-form-item label="日期：">
        <div class="condition">
          <el-switch
            v-model="preference.date.enable"
            :disabled="!accountId"
            class="enable"
          />
          <!-- 操作符选择 -->
          <el-select :disabled="!accountId || !preference.date.enable" v-model="preference.date.operator" placeholder="选择条件" class="operator">
            <el-option v-for="op in operators.date" :key="op.value" :label="op.label" :value="op.value" />
          </el-select>
          <div class="values">
            <el-input-number :disabled="!accountId || !preference.date.enable" v-if="preference.date.operator === operator.recent" class="value"
              v-model="preference.date.recent" :min="1" :max="100" controls-position="right">
              <template #suffix>
                <span>天</span>
              </template>
            </el-input-number>
            <el-date-picker
              v-else-if="preference.date.operator === operator.between"
              v-model="preference.date.values"
              :disabled="!accountId || !preference.date.enable"
              type="daterange"
              placeholder="选择日期"
              :clearable="false"
              :editable="false" />

            <el-date-picker
              v-else v-model="preference.date.values[0]"
              type="date"
              :disabled="!accountId || !preference.date.enable"
              :editable="false"
              :clearable="false"
              placeholder="选择日期" />


          </div>
        </div>

      </el-form-item>
      <el-form-item label="佣金：">
        <div class="condition">
          <el-switch
            v-model="preference.commission.enable"
            :disabled="!accountId"
            class="enable"
          />
          <!-- 操作符选择 -->
          <el-select :disabled="!accountId || !preference.commission.enable" v-model="preference.commission.operator" placeholder="选择条件" class="operator">
            <el-option v-for="op in operators.number" :key="op.value" :label="op.label" :value="op.value" />
          </el-select>
          <div class="values">
            <template v-for="(value, idx) in preference.commission.values" :key="idx">
              <div class="symbol" v-if="idx !== 0">-</div>
              <el-input-number :disabled="!accountId || !preference.commission.enable" class="value" v-model="preference.commission.values[idx]" :min="0" :max="100"
                controls-position="right">
                <template #suffix>
                  <span :data-value="value">%</span>
                </template>
              </el-input-number>

            </template>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="类目：">
        <div class="condition">
          <el-switch
            v-model="preference.category.enable"
            :disabled="!accountId"
            class="enable"
          />

          <div class="category-card">
          <div class="category-item" v-for="(item, idx) in preference.category.items" :key="idx" :data-id="item.second">
            <el-select
              v-model="preference.category.items[idx].first"
              :disabled="!accountId || !preference.category.enable"
              class="category-first category-select"
              placeholder="一级类目"
              filterable
              @change="onFirstCategoryChange(idx)">
              <el-option v-for="(option, idx) in categories" :key="idx" :label="option.name" :value="option.id" />
            </el-select>
            <el-select
              v-model="preference.category.items[idx].second"
              :disabled="!accountId || !preference.category.enable"
              class="category-second category-select"
              placeholder="二级类目"
              filterable
              @change="onCategoryChange(idx)">
              <el-option
                v-for="(option, idx) in categories.filter(item => item.id === preference.category.items[idx].first)[0]?.children"
                :key="idx" :label="option.name" :value="option.id" />
            </el-select>
            <el-input-number
              v-model="preference.category.items[idx].weight"
              class="weight"
              :disabled="!accountId || !preference.category.enable"
              :min="1"
              :max="100"
              placeholder="权重"
              controls-position="right"></el-input-number>

            <el-button
              type="danger"
              class="btn-operator btn-remove"
              :disabled="!accountId || !preference.category.enable"
              icon="delete"
              @click="removeCategoryCondition(idx)"></el-button>
          </div>
          <el-button
            type="success"
            plain
            class="btn-operator btn-add"
            :disabled="!accountId || !preference.category.enable"
            icon="Plus"
            @click="addCategoryCondition"></el-button>
        </div>
        </div>

      </el-form-item>

    </el-form>

    <template #footer v-if="showSave">
      <div class="card-footer">
        <div></div>
        <el-button type="warning" :disabled="!accountId" @click="save">存档</el-button>
      </div>
    </template>
  </el-card>

</template>

<script setup lang="ts">
import { toRaw, ref, watch, onMounted } from 'vue'
import * as categoryService from '@/api/service/CategoryService'
import * as accountService from '@/api/service/AccountService'
import { Operator, OperatorGroup } from '@/framework/common/constants';
import DateUtil from '@/framework/utils/date-util';

defineOptions({ name: "PreferencePanel" });

const props = defineProps({
  modelValue: {
    type: Object
  },
  showSave:{
    type: Boolean,
    default: true
  }
})


const emit = defineEmits(['update:modelValue', 'archive'])
let accountId = ref(null)
let recordId = null

const loading = ref(false)
const globalVal = globalThis as any
const categories = ref<any>([])
const showSave = ref(props.showSave)

const operator = ref(Operator)
// 操作符配置
const operators = ref(OperatorGroup)

const sevenDays = DateUtil.before(7);
const preference = ref<Preference>({
  date: {
    enable: true,
    operator: Operator.recent,
    values: [sevenDays],
    recent: 7
  },
  category: {
    enable: true,
    items: [{
      first: null,
      second: null,
      weight: 10
    }]
  },
  commission: {
    enable: true,
    operator: Operator.greaterEqual,
    values: [3]
  }
})


/**
 * 加载分类信息
 */
async function loadCategories(): Promise<any> {
  loading.value = true;
  categoryService.categories().then(items => {
    categories.value = items;
  }).finally(()=>{
    loading.value = false;
  })

}

/**
 * 新增分类
 */
function addCategoryCondition(): void {
  preference.value.category.items.push({
    first: null,
    second: null,
    weight: 10 // 权重
  })
}

/**
 *
 * @param index 删除分类
 */
function removeCategoryCondition(index): void {
  preference.value.category.items.splice(index, 1);
}

/**
 * 一级类目变更
 * @param index
 */
function onFirstCategoryChange(index): void {
  preference.value.category.items[index].second = null
}
/**
 * 分类变化
 */
function onCategoryChange(index): void {
  const condition = preference.value.category.items[index]
  if(!condition){
    return
  }
  preference.value.category.items.forEach((item, idx) => {
    if (idx !== index && (item.first === condition.first && item.second === condition.second)) {
      preference.value.category.items[index].second = null;
      globalVal.error(`分类[${item.first}/${item.second}]已存在`);
      return
    }
  })
}

/**
 * 存档
 */
function save(): void {
  if(!accountId.value){
    globalVal.error('账号ID不能为空')
    return
  }
  const payload = {
    '账号ID': props?.modelValue?.accountId,
    '偏好设置': JSON.stringify(toRaw(preference.value))
  }
  loading.value = true;
  const promise = recordId
  ? accountService.updateRecord(recordId, payload)
  : accountService.addRecord(payload);
  promise.then(response => {
     const record = globalVal.parseFeishuRecord(response.data.record);
     console.log(response.data.record)
     console.log(record);
     emit('archive', {
      data: record
     });
     globalVal.success('存档成功')
  }).catch(e=> {
    console.error(e)
    globalVal.error('存档失败')
  }).finally(()=>{
    loading.value = false;
  })
}

watch(
  () => preference.value.date,
  (newValue) => {
    if (newValue.operator === Operator.between && newValue.values.length === 1) {
      newValue.values[1] = newValue.values[0]
    }
    else if (newValue.operator !== Operator.between && newValue.values.length > 1) {
      newValue.values = [newValue.values[0]]
    }
  },
  { deep: true }
)

watch(
  () => preference.value.commission,
  (newValue) => {
    if (newValue.operator === Operator.between && newValue.values.length === 1) {
      newValue.values[1] = newValue.values[0]
    }
    else if (newValue.operator !== Operator.between && newValue.values.length > 1) {
      newValue.values = [newValue.values[0]]
    }
  },
  { deep: true }
)

watch(preference, (newValue) => {
  emit('update:modelValue', {
    accountId: accountId.value,
    preference: toRaw(newValue),
    recordId: recordId
  })
}, {
  deep: true
})

watch(() => props.modelValue, (newVal) => {
  if(newVal){
    const data = toRaw(newVal);
    accountId.value = data.accountId;
    recordId = data.recordId
    preference.value = data.preference || {
        date: {
          enable: true,
          operator: Operator.recent,
          values: [sevenDays],
          recent: 7
        },
        category: {
          enable: true,
          items: [{
            first: null,
            second: null,
            weight: 10 // 权重
          }]
        },
        commission: {
          enable: true,
          operator: Operator.greaterEqual,
          values: [3]
        }
      } as Preference
  }
}, { immediate: true })

onMounted(() => {
  loadCategories();
})

</script>

<style lang="scss" scoped>
.preference-panel {
  width: 100%;

  :deep(.el-card__header) {
    padding: 10px;
  }

  :deep(.el-card__footer) {
    padding: 10px;
  }

}

.card-header {
  display: flex;
  justify-content: space-between;
  padding-left: 10px;

  .card-header-text {
    font-size: 14px;
  }
}

.card-footer {
  display: flex;
  justify-content: space-between;
}


.condition {
  display: flex;
  margin-bottom: 10px;

  .enable{
    margin-right: 20px;
  }

  .operator {
    width: 120px;
    margin-right: 8px;
  }

  .values {
    display: flex;

    .value {
      width: 120px;
    }

    .symbol {
      margin: 0 10px;
    }
  }

}

.category-card {
  width: 100%;

  .category-item {
    display: flex;
    margin-bottom: 10px;

    &:first-child {
      margin-top: 0;
    }

    .weight {
      width: 120px;
      margin-right: 10px;
    }
  }
  .btn-add{
    width: 250px;
  }
}
</style>
